package net.hn.hnms.biz.quality.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.quality.domain.CoalQualityPlan;
import net.hn.hnms.biz.quality.enums.PlanDateType;
import net.hn.hnms.biz.quality.mapper.CoalQualityPlanMapper;
import net.hn.hnms.biz.quality.request.CoalQualityPlanReq;
import net.hn.hnms.biz.quality.service.ICoalQualityPlanService;
import net.hn.hnms.biz.quality.vo.CoalQualityDataVo;
import net.hn.hnms.biz.quality.vo.CoalQualityPlanVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ly
 * 煤质计划表服务层实现
 * @date 2022-09-09
 */

@Service
public class CoalQualityPlanServiceImpl  extends BaseService<CoalQualityPlan, CoalQualityPlanVO> implements ICoalQualityPlanService {

    private CoalQualityPlanMapper coalQualityPlanMapper;

    public CoalQualityPlanServiceImpl(CoalQualityPlanMapper coalQualityPlanMapper) {
        this.coalQualityPlanMapper = coalQualityPlanMapper;
    }

    /**
     * @param coalQualityPlanReq
     * @param pageQuery       查询煤质分析计划列表
     */
    @Override
    public ResponsePage<CoalQualityPlanVO> selectPageList(CoalQualityPlanReq coalQualityPlanReq, PageQuery pageQuery) {

        Page<CoalQualityPlan> page = coalQualityPlanMapper.selectPage(pageQuery.build(), buildQuery(coalQualityPlanReq).orderByDesc(CoalQualityPlan::getStartDate));

        return new ResponsePage<>(convert(page.getRecords(),CoalQualityPlanVO.class, true), page.getTotal());
    }

    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<CoalQualityPlan> 查询条件
     */
    private LambdaQueryWrapper<CoalQualityPlan> buildQuery(CoalQualityPlanReq req) {
        return new LambdaQueryWrapper<CoalQualityPlan>()
                .like(StrUtil.isNotBlank(req.getPlanCode()), CoalQualityPlan::getPlanCode, req.getPlanCode())
                .like(StrUtil.isNotBlank(req.getPlanName()), CoalQualityPlan::getPlanName, req.getPlanName())
                .like(StrUtil.isNotBlank(req.getPlanType()), CoalQualityPlan::getPlanType, req.getPlanType())
                .eq(StrUtil.isNotBlank(req.getStatus()), CoalQualityPlan::getStatus, req.getStatus())
                .eq(StrUtil.isNotBlank(req.getMineCode()),CoalQualityPlan::getMineCode,req.getMineCode());
    }

    /**
     * @param CoalQualityPlan 查询煤质分析计划列表
     */
    @Override
    public List<CoalQualityPlanVO> selectList(CoalQualityPlanReq CoalQualityPlan) {
        List<CoalQualityPlan> list = coalQualityPlanMapper.selectList(buildQuery(CoalQualityPlan));
        return convert(list, CoalQualityPlanVO.class, false);
    }

    /**
     * @param req 新增煤质分析计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(CoalQualityPlanReq req) {
        CoalQualityPlan insertObj = new CoalQualityPlan();
        BeanUtil.copyProperties(req, insertObj, "startDate", "endDate");
        if (StrUtil.equals(req.getPlanType(), PlanDateType.MONTH.getCode())) {
            String startDate = req.getStartDate().substring(0,7);
            insertObj.setStartDate(DateUtil.parseDate(startDate + "-01"));
            insertObj.setEndDate(DateUtil.endOfMonth(insertObj.getStartDate()));
        } else {
            String startDate = req.getStartDate().substring(0,4);
            insertObj.setStartDate(DateUtil.parseDate(startDate + "-01-01"));
            insertObj.setEndDate(DateUtil.parseDate(startDate+ "-12-31"));
        }
        //自动生成 计划名称 计划编号
        insertObj.setPlanName(generatePlanName(req.getPlanType(),insertObj.getStartDate()));
        insertObj.setPlanCode(generatePlanCode(req.getPlanType(),insertObj.getEndDate()));
        insertObj.setStatus("0");
        QueryWrapper<CoalQualityPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_code", insertObj.getPlanCode());
        if (coalQualityPlanMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return coalQualityPlanMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除 id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        coalQualityPlanMapper.deleteBatchIds(idList);
    }

    /**
     * @param req 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(CoalQualityPlanReq req) {
        if (StrUtil.isBlank(req.getCoalQualityPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        CoalQualityPlan updateObj = new CoalQualityPlan();
        BeanUtil.copyProperties(req, updateObj, "startDate", "endDate");
        if (StrUtil.equals(req.getPlanType(), PlanDateType.MONTH.getCode())) {
            String startDate = req.getStartDate().substring(0,7);
            updateObj.setStartDate(DateUtil.parseDate(startDate + "-01"));
            updateObj.setEndDate(DateUtil.endOfMonth(updateObj.getStartDate()));
        } else {
            String startDate = req.getStartDate().substring(0,4);
            updateObj.setStartDate(DateUtil.parseDate(startDate + "-01-01"));
            updateObj.setEndDate(DateUtil.parseDate(startDate + "-12-31"));
        }
        updateObj.setPlanName(generatePlanName(req.getPlanType(),updateObj.getStartDate()));
        updateObj.setPlanCode(generatePlanCode(req.getPlanType(),updateObj.getEndDate()));
        QueryWrapper<CoalQualityPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_code", updateObj.getPlanCode());
        queryWrapper.ne("coal_quality_plan_id", updateObj.getCoalQualityPlanId());
        if (coalQualityPlanMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = coalQualityPlanMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public CoalQualityPlanVO selectDetailById(String id) {
        CoalQualityPlan coalQualityPlan = coalQualityPlanMapper.selectById(id);
        if (coalQualityPlan == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(coalQualityPlan, CoalQualityPlanVO.class);
    }


    /**
     * 启用/禁用
     *
     * @param id     数据id
     * @param status status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            CoalQualityPlan planMining = coalQualityPlanMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = coalQualityPlanMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }

            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }

    @Override
    public List<CoalQualityDataVo> selectListByDate(String mineCode) {
        return coalQualityPlanMapper.selectListByDate(mineCode);
    }
}
